package com.chaosj.webmagic.convert;

import com.chaosj.webmagic.dto.SearchResponseDto;
import com.chaosj.webmagic.dto.gushiwen.HomeResponseDto;
import com.chaosj.webmagic.dto.SearchEnums;
import org.apache.commons.lang3.StringUtils;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.selector.Selectable;

import java.util.stream.Collectors;

/**
 * @className: HomeShiGeConvertHandler
 * @description:
 * @author: caoyangjie
 * @date: 2021/8/11
 **/
public class HomeShiGeConvertHandler extends AbstractConvertPage<HomeResponseDto> {

    @Override
    public void convert(Page page) {
        Selectable selectable = page.getHtml().xpath("//div[@class='cont']");
        SearchResponseDto hrd = createOrGet(page);
        selectable.nodes().forEach(selected->{
            // 获取 诗名
            String tip = selected.xpath("//p//b/text()").get();
            if(StringUtils.isEmpty(tip)){
                return;
            }
            // 获取 访问地址
            String target = holdTarget(selected.xpath("//p//a/@href").get());
            // 获取 作者名
            String author = selected.xpath("//p/a[1]/text()").all().stream().skip(0).collect(Collectors.joining(""));
            // 获取 朝代
            String dynasty = selected.xpath("//p/a[2]/text()").get();
            // 获取 内容
            String content = selected.xpath("//div[@class='contson']/text()").get();
            if( content.trim().length()==0 ){
                content = selected.xpath("//div[@class='contson']/p/text()").all().stream().collect(Collectors.joining());
            }
            hrd.addObject("poetry", tip, target, author, dynasty, content);
        });
    }

    @Override
    public String holdTarget(String target){
        return target;
    }

    @Override
    public boolean support(SearchEnums instance) {
        return SearchEnums.HOME.equals(instance);
    }
}
